/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */


function TreeNode(val) {
  this.val = val;
  this.left = this.right = null;
}


var buildTree = function (preorder, inorder) {
  if (preorder.length != 0) {
    // 子树根节点
    let root = preorder[0]
    let node = new TreeNode(root)
    let lt_in = [];
    let lt_pre = []

    

    var index
    for (index = 0; inorder[index] != root; index++) {
      // 构建 中序左子树
      lt_in.push(inorder[index])

      // 构建 前序左子树
      lt_pre.push(preorder[index + 1])
    }
    index++

    let rt_in = []; let rt_pre = []
    for (; index < preorder.length; index++) {
      // 构建 中序右子树
      rt_in.push(inorder[index])

      // 构建 前序右子树
      rt_pre.push(preorder[index])
    }
    if (lt_pre.length == 0 && rt_pre.length == 0) {
      node.left = null
      node.right = null
      return node
    }

    let lt = buildTree(lt_pre, lt_in)
    let rt = buildTree(rt_pre, rt_in)
    node.left = lt
    node.right = rt
    return node
  }
  return null
};

let a = buildTree([1, 2], [1, 2])
console.log(a);